/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.swirrel.installer;

import java.awt.Component;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import org.swirrel.annotation.ChangeUpdate;
import org.swirrel.annotation.InsertUpdate;
import org.swirrel.annotation.RemoveUpdate;
import org.swirrel.listener.SwirrelDocumentListener;
import org.swirrel.util.MethodCall;
import java.lang.annotation.Annotation;

/**
 *
 * @author Gronau
 */
public class DocumentListenerInstaller extends AbstractListenerInstaller implements SwirrelListenerInstaller {

    public DocumentListenerInstaller() {
        super(Arrays.<Class<? extends Annotation>>asList(InsertUpdate.class,
                RemoveUpdate.class, ChangeUpdate.class),
                Arrays.<Class<?>>asList(JTextComponent.class));
    }

    public boolean isListenerAlreadySet(Object obj) {
        Document doc = ((JTextComponent) obj).getDocument();
        if (doc instanceof AbstractDocument) {
            AbstractDocument ad = (AbstractDocument) doc;
            for (DocumentListener dl : ad.getDocumentListeners()) {
                if (dl instanceof SwirrelDocumentListener) {
                    return true;
                }
            }
        }
        return false;
    }

    public void registerListener(Field field, Component comp, List<MethodCall> methodCalls) throws IllegalAccessException {
        Object obj = field.get(comp);
        ((JTextComponent) obj).getDocument().addDocumentListener(
                new SwirrelDocumentListener(methodCalls.get(0),
                methodCalls.get(1), methodCalls.get(2)));
    }
}
